<template>
  <DetailsFormBox :title="dataInfo?.table?.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
  ]" :loading="data.loading" :json="dataInfo">
    <template #default="{ form }">
      <div class="formMain">
        <ElFormItemBox label="物料编号" :prop="`goodsCode`">
          <ElInputBox :data="form" dataName="goodsCode" placeholder="系统自动生成" disabled />
        </ElFormItemBox>
        <ElFormItemBox label="供应商" :prop="`supplierCode`" isRules>
          <ElSelectBox :data="form" dataName="supplierCode" :options="options.supplier" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="物料类型" :prop="`categoryCode`" isRules>
          <ElSelectBox :data="form" dataName="categoryCode" :options="options.category" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="物料分组" :prop="`groupCode`" isRules>
          <ElSelectBox :data="form" dataName="groupCode" :options="options.goodGroup" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="物料名称" :prop="`goodsName`" isRules>
          <ElInputBox :data="form" dataName="goodsName" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="规格型号" :prop="`specificationName`" isRules>
          <ElInputBox :data="form" dataName="specificationName" :disabled="!isEdit" @changeBtn="(value: any) => {
            if (![NaN, 'NaN'].includes(Number(value))) {
              form.specificationJsValue = Number(value) / 1000;
            } else {
              form.specificationJsValue = 1;
            }
          }" />
        </ElFormItemBox>
        <ElFormItemBox label="使用单位" :prop="`goodsUnitCode`">
          <ElSelectBox :data="form" dataName="goodsUnitCode" :options="options.unit" :disabled="!isEdit" @changeBtn="(value: any) => {
            form.priceUnitCode = value
          }" />
        </ElFormItemBox>
        <ElFormItemBox ElFormItemBox label=" 计价单位" :prop="`priceUnitCode`">
          <ElSelectBox :data="form" dataName="priceUnitCode" :options="options.unit" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="转换比例" :prop="`specificationJsValue`" isRules>
          <ElNumberBox :data="form" dataName="specificationJsValue" :disabled="!isEdit" />
        </ElFormItemBox>
        <ElFormItemBox label="采购单价" :prop="`goodsPrice`">
          <ElNumberBox :data="form" dataName="goodsPrice" unit="元" disabled />
        </ElFormItemBox>
        <ElFormItemBox label="税率" :prop="`taxRate`">
          <ElNumberBox :data="form" dataName="taxRate" :max="100" :min="0" unit="%" @changeBtn="() => {
            proxy.$setTaxRate(form, {
              taxRate: 'taxRate', // 税率
              taxExcludedUnitPrice: 'averagePriceBeforeTax', // 未税单价
              taxIncludedUnitPrice: 'averagePrice', // 含税单价
            })
          }" />
        </ElFormItemBox>
        <ElFormItemBox label="含税均价" :prop="`averagePrice`" isRules>
          <ElNumberBox :data="form" dataName="averagePrice" unit="元" :disabled="!isEdit" @changeBtn="() => {
            proxy.$setTaxInclusiveUnitPrice(form, {
              taxRate: 'taxRate', // 税率
              taxExcludedUnitPrice: 'averagePriceBeforeTax', // 未税单价
              taxIncludedUnitPrice: 'averagePrice', // 含税单价
            })
          }" />
        </ElFormItemBox>
        <ElFormItemBox label="未税均价" :prop="`averagePriceBeforeTax`">
          <ElNumberBox :data="form" dataName="averagePriceBeforeTax" unit="元" :disabled="true" />
        </ElFormItemBox>
        <ElFormItemBox label="备注" :prop="`stockGoodsDesc`">
          <ElInputBox :data="form" dataName="stockGoodsDesc" type="textarea" :disabled="!isEdit" />
        </ElFormItemBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { useListComponent } from '../pageTs'; // 引入逻辑
const { dataInfo, options } = useListComponent();
import { reactive, onMounted, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance() as any;
const data = reactive({
  loading: false,
  loadingMsg: '',
  form: {
    stockGoodsID: null, // 库存物料主键ID
    creator: "", // 创建人员
    createTime: "", // 创建时间
    stockGoodsDesc: "", // 备注/描述
    goodsCode: "", // 物料编码
    goodsName: "", // 物料名称
    specificationCode: "", // 规格编号
    specificationName: "", // 规格名称
    supplierName: "", // 供应商名称
    supplierCode: "", // 供应商编码
    isDisable: 0, // 启用状态：0启用；1禁用
    state: 1, // 规格状态：0待确认；1已确认；2已作废
    goodsGroupName: "", // 物料分组名称
    goodsGroupCode: "", // 物料分组编码
    goodsTypeName: "", // 物料类型名称
    goodsTypeCode: "", // 物料类型编码
    goodsUnit: "", // 物料单位
    goodsUnitCode: "", // 物料单位编码
    priceUnit: "", // 计价单位
    priceUnitCode: "", // 计价单位编码
    specificationJsValue: null, // 转换比例
    goodsPrice: null, // 含税单价
    goodsPriceBeforeTax: null, // 未税单价
    purchaseMaxPrice: null, // 采购最高价
    purchaseMinPrice: null, // 采购最低价
    purchaseAvgPrice: null, // 采购均价
    searchHotKeys: "", // 快捷键
    reason: "", // 作废原因
    isPriceAdjustment: false, // 是否已经调价
    goodsPriceAdjustmentTime: "", // 物料核价日期
    taxRate: 13, // 税率（如：13%）
    totalStockQuantity: null, // 总库存数量
    totalCost1: null, // 所有含税入库价值（入库数量 * 入库单价）
    totalCost2: null, // 所有含税出库价值（出库数量 * 出库单价）
    totalCostBeforeTax1: null, // 所有未税入库价值
    totalCostBeforeTax2: null, // 所有未税出库价值
    averagePrice: null, // 含税均价
    averagePriceBeforeTax: null // 未税均价
  },
});
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
import { sendMsg } from '@/utils/crossTagMag.ts';
const saveBtn = (form: any, isConfirm: boolean = false) => {
  const _isAddSpecification = route.query.type === '1' && !!route.query.specificationCode
  if (form.specificationCode) {
    //修改物料
    proxy.$api.Goods.UpdateGoods(form)
      .then((res: any) => {
        if (isConfirm) {
          _setState(form.specificationCode)
        } else {
          _sun()
        }
      })
      .catch(() => { });
  } else if (_isAddSpecification) {
    //添加物料规格
    proxy.$api.GoodsSpecification.AddSpecification(form)
      .then((res: any) => {
        if (isConfirm) {
          _setState(res)
        } else {
          _sun()
        }
      })
      .catch(() => { });
  } else {
    //添加物料
    proxy.$api.Goods.AddGoods(form)
      .then((res: any) => {
        if (isConfirm) {
          _setState(res.specificationCode)
        } else {
          _sun()
        }
      })
      .catch(() => { });
  }
  function _sun() {
    proxy.$message('保存成功')
    sendMsg('save', true);
    // getForm()
    window.close();
  }
  function _setState(specificationCode: any) {
    proxy.$api.Goods.UpdateGoodsSpecificationState({
      specificationCode: specificationCode,
      type: 1, //	要修改的字段（0：启用状态，1：物料状态）
      state: 1, //Type为0时，传0为启用，1为禁用，Type为1时，传1为确认，2为作废
      reason: '', //作废原因
    })
      .then((res: any) => {
        _sun()
      })
      .catch(() => { });
  }
};
const isEdit = ref(true)
const getForm = () => {
  let _query: any = route.query
  const _isAdd: any = route.query.type === '1'
  if (!_query.specificationCode) {
    data.loading = false
    return
  }
  proxy.$api.Goods.GetGoodsSpecificationViewDetail({
    queryBy: 1,
    queryValue: _query.specificationCode,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = (['1', '2'].includes(_query.type)) || res.state === 0
      data.form = {
        ...res,
        groupCode: res.goodsGroupCode,
        categoryCode: res.goodsTypeCode,
        taxRate: res.taxRate,
        specificationJsValue: _isAdd ? null : res.specificationJsValue,//转换比例
        specificationName: _isAdd ? '' : res.specificationName,//规格型号
        specificationCode: _isAdd ? '' : res.specificationCode,//规格型号code
        stockGoodsName: _isAdd ? '' : res.specificationName,//规格型号
        searchHotKeys: _isAdd ? '' : res.searchHotKeys,//	搜索热键
        stockGoodsDesc: _isAdd ? '' : res.stockGoodsDesc,//物料说明
      }
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
import { goodGroup, getGoodType, } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm()
  goodGroup(options, 'goodGroup')
  getGoodType(options, 'category', {
    DictionaryCode: 'GoodsCategory',
  })
  getGoodType(options, 'unit', {
    DictionaryCode: 'GoodsUnit',
  })
});
</script>
